package com.example.myapplicationfinalwork.ui.setting;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplicationfinalwork.MainActivity;
import com.example.myapplicationfinalwork.R;
import com.example.myapplicationfinalwork.common.Analysis;
import com.example.myapplicationfinalwork.common.HistoryWeather;
import com.example.myapplicationfinalwork.common.db.dao.CityDao;
import com.example.myapplicationfinalwork.common.db.database.CityDatabase;
import com.example.myapplicationfinalwork.common.db.database.UserDatabase;
import com.example.myapplicationfinalwork.common.db.table.InterestedCity;
import com.example.myapplicationfinalwork.common.db.table.UserTable;
import com.example.myapplicationfinalwork.databinding.FragmentSettingBinding;
import com.example.myapplicationfinalwork.model.MapViewModel;
import com.example.myapplicationfinalwork.model.SettingViewModel;
import com.example.myapplicationfinalwork.ui.history.HistoryFragment;
import com.example.myapplicationfinalwork.util.MyLayoutManager;
import com.example.myapplicationfinalwork.util.WeatherChartView;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;

import java.util.ArrayList;
import java.util.List;

public class SettingFragment extends Fragment {

    private SettingViewModel settingViewModel;
    private MapViewModel mapViewModel;
    private FragmentSettingBinding binding;
    private CityPickerView cityPickerView=new CityPickerView();
    private boolean editable=false;
    private List<String> listStr=new ArrayList<>();


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        settingViewModel = new ViewModelProvider(this).get(SettingViewModel.class);
        mapViewModel= new ViewModelProvider(getActivity(),new ViewModelProvider.NewInstanceFactory()).get(MapViewModel.class);

        binding = FragmentSettingBinding.inflate(inflater, container, false);
        binding.tvSettingCity.setText(((MainActivity)getActivity()).localedCity);
        binding.tvSettingUsername.setText(((MainActivity)getActivity()).username);

        /*binding.test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<InterestedCity> tmp= CityDatabase.getInstance().getCityDao().test();
                for(InterestedCity u:tmp){
                    u.setUsername(((MainActivity)getActivity()).username);
                    CityDatabase.getInstance().getCityDao().updateCity(u);
                }
            }
        });*/

        settingViewModel.getCityName(((MainActivity)getActivity()).username).observe(getViewLifecycleOwner(), new Observer<List<String>>() {
            @Override
            public void onChanged(List<String> strings) {
                listStr=strings;
                initRecycleView();
            }
        });

        mapViewModel.getCity(((MainActivity)getActivity()).localedCity).observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                binding.tvSettingCity.setText(s);
            }
        });

        binding.btnSettingModify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editable=!editable;
                Analysis.EditTextEnable(editable,binding.etSettingPwd);
                binding.btnSettingModify.setText(editable?"确认修改":"修改信息");
                if(editable==false){
                    Toast.makeText(getContext(),"信息修改成功",Toast.LENGTH_SHORT).show();

                    UserTable user= UserDatabase.getInstance().getUserDao().getUser(((MainActivity)getActivity()).username);
                    if(user==null){
                        // TODO:登录注册页面进行数据库写入
                        user=new UserTable(((MainActivity)getActivity()).username,"123456");
                        UserDatabase.getInstance().getUserDao().addUser(user);
                        Toast.makeText(getContext(), "数据库: 添加初始化数据 成功", Toast.LENGTH_SHORT).show();
                    }
                    user.setPwd(binding.etSettingPwd.getText().toString());
                    user.setDisplayNum(Integer.valueOf(binding.settingNumTv.getText().toString()));
                    user.setAutoLogin(binding.settingCheckboxAutoLogin.isChecked());
                    UserDatabase.getInstance().getUserDao().updateUser(user);

                    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean("isAutoLogin",binding.settingCheckboxAutoLogin.isChecked());
                    editor.commit();

                    InterestedCity iCity=new InterestedCity();
                    iCity.setUsername(((MainActivity)getActivity()).username);
                    iCity.setCityName(((MainActivity)getActivity()).localedCity);
                    iCity.setTime(Analysis.getDateFormat());

                    //--清除数据库已有城市数据
                    List<InterestedCity> tmp=CityDatabase.getInstance().getCityDao().getSelectedCity(((MainActivity)getActivity()).localedCity,((MainActivity)getActivity()).username);
                    for(InterestedCity vv:tmp){
                        CityDatabase.getInstance().getCityDao().deleteCity(vv);
                    }
                    CityDatabase.getInstance().getCityDao().addCity(iCity);

                    Toast.makeText(getContext(), "数据库: 修改数据 成功", Toast.LENGTH_SHORT).show();
                }
            }
        });

        initPage();
        initCityPicker();
        initNumBtn();


        return binding.getRoot();
    }

    void initPage(){
        UserTable user=UserDatabase.getInstance().getUserDao().getUser(((MainActivity)getActivity()).username);
        binding.etSettingPwd.setText(user.getPwd());
        binding.settingNumTv.setText(String.valueOf(user.getDisplayNum()));
        binding.settingCheckboxAutoLogin.setChecked(user.isAutoLogin());
    }

    void initNumBtn(){
        TextView tv=binding.settingNumTv;
        binding.settingNumAddBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num=Integer.valueOf(tv.getText().toString());
                if(num>=10){
                    Toast.makeText(getContext(),"城市显示个数为4~10个",Toast.LENGTH_SHORT).show();
                    return;
                }
                ++num;
                tv.setText(String.valueOf(num));
            }
        });

        binding.settingNumSubBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num=Integer.valueOf(tv.getText().toString());
                if(num<=4){
                    Toast.makeText(getContext(),"城市显示个数为4~10个",Toast.LENGTH_SHORT).show();
                    return;
                }
                --num;
                tv.setText(String.valueOf(num));
            }
        });
    }

    void initRecycleView(){
        MyLayoutManager layout = new MyLayoutManager();
        layout.setAutoMeasureEnabled(true);
        binding.rvSetting.setLayoutManager(layout);
        MyAdapter myAdapter=new MyAdapter();
        binding.rvSetting.setAdapter(myAdapter);

    }

    void initCityPicker(){
        cityPickerView.init(getContext());
        CityConfig cityConfig=new CityConfig.Builder().province("浙江省").city("杭州市").district("余杭区").build();
        cityPickerView.setConfig(cityConfig);

        binding.viewSettingNowCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(editable==false) return;

                cityPickerView.showCityPicker();
                cityPickerView.setOnCityItemClickListener(new OnCityItemClickListener() {
                    @Override
                    public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                        super.onSelected(province, city, district);

                        String selectedCity=city.toString();
                        binding.tvSettingCity.setText(selectedCity);
                        mapViewModel.setCity(selectedCity);
                        ((MainActivity)getActivity()).localedCity = selectedCity;
                        Log.i("myDebug", "设置页面: "+((MainActivity)getActivity()).localedCity);
                        showCityChanged(selectedCity);
                    }
                });
            }
        });

        binding.btnSettingAddCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cityPickerView.showCityPicker();
                cityPickerView.setOnCityItemClickListener(new OnCityItemClickListener() {
                    @Override
                    public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                        super.onSelected(province, city, district);
                        String selectedCity=city.toString();
                        Toast.makeText(getContext(),selectedCity,Toast.LENGTH_SHORT).show();
                        String str=Analysis.getDateFormat();
                        InterestedCity iCity=new InterestedCity();
                        iCity.setTime(str);
                        iCity.setCityName(selectedCity);
                        iCity.setUsername(((MainActivity)getActivity()).username);

                        List<InterestedCity> iTmp=CityDatabase.getInstance().getCityDao().getSelectedCity(selectedCity,((MainActivity)getActivity()).username);
                        for(InterestedCity v:iTmp){
                            CityDatabase.getInstance().getCityDao().deleteCity(v);
                        }
                        CityDatabase.getInstance().getCityDao().addCity(iCity);
                        settingViewModel.setCityName(((MainActivity)getActivity()).username);
                    }
                });
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private void showCityChanged(String city){
        Notification notification;
        Notification.Builder builder;
        //创建一个通知管理器
        NotificationManager notificationManager= (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder=new Notification.Builder(getContext(),"5996773");
        }else {
            builder=new Notification.Builder(getContext());
        }
        //设置标题
        builder.setContentTitle("城市变更");
        //设置内容
        builder.setContentText("当前城市修改为: "+city);
        //设置状态栏显示的图标，建议图标颜色透明
        builder.setSmallIcon(R.drawable.ic_logo);
        // 设置通知灯光（LIGHTS）、铃声（SOUND）、震动（VIBRATE）、（ALL 表示都设置）
        builder.setDefaults(Notification.DEFAULT_ALL);
        //灯光三个参数，颜色（argb）、亮时间（毫秒）、暗时间（毫秒）,灯光与设备有关
        builder.setLights(Color.RED, 200, 200);
        // 震动，传入一个 long 型数组，表示 停、震、停、震 ... （毫秒）
        builder.setVibrate(new long[]{0, 200, 200, 200, 200, 200});
        // 通知栏点击后自动消失
        builder.setAutoCancel(true);
        builder.setPriority(Notification.PRIORITY_HIGH);

        //设置下拉之后显示的图片
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_weather));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("5996773", "安卓10a", NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true);//是否在桌面icon右上角展示小红点
            channel.setLightColor(Color.GREEN);//小红点颜色
            channel.setShowBadge(false); //是否在久按桌面图标时显示此渠道的通知
            notificationManager.createNotificationChannel(channel);
        }
        notification=builder.build();
        notificationManager.notify(1,notification);
    }

    class MyAdapter extends RecyclerView.Adapter<SettingFragment.MyViewHoder> {

        @NonNull
        @Override
        public SettingFragment.MyViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //View view = View.inflate(getContext(), R.layout.rv_desc_list, null);
            View view =  LayoutInflater.from(getContext()).inflate(R.layout.rv_setting_tv, parent, false);
            SettingFragment.MyViewHoder myViewHoder = new SettingFragment.MyViewHoder(view);
            myViewHoder.mCity.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    AlertDialog.Builder builder=new AlertDialog.Builder(getContext());
                    builder.setTitle("提示：");
                    builder.setMessage("确定删除城市"+ myViewHoder.mCity.getText().toString()+"?");

                    //设置确定按钮
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(getContext(),"确定删除",Toast.LENGTH_SHORT).show();
                            List<InterestedCity> iTmp=CityDatabase.getInstance().getCityDao().getSelectedCity(myViewHoder.mCity.getText().toString(),((MainActivity)getActivity()).username);
                            for(InterestedCity v:iTmp){
                                CityDatabase.getInstance().getCityDao().deleteCity(v);
                            }
                            settingViewModel.setCityName(((MainActivity)getActivity()).username);
                        }
                    });
                    //设置取消按钮
                    builder.setNegativeButton("取消",null);
                    //显示提示框
                    builder.show();
                    return false;
                }
            });
            return myViewHoder;
        }

        @Override
        public void onBindViewHolder(@NonNull SettingFragment.MyViewHoder holder, int position) {
            String str=listStr.get(position);
            holder.mCity.setText(str);
        }

        @Override
        public int getItemCount() {
            return listStr.size();
        }
    }

    class MyViewHoder extends RecyclerView.ViewHolder {
        TextView mCity;

        public MyViewHoder(@NonNull View itemView) {
            super(itemView);
            mCity=itemView.findViewById(R.id.rv_setting_li_tv);
        }
    }
}